package com.uca.sisbec.commons;

import com.uca.sisbec.mapping.Usuario;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class HibernateAction extends SisbecAction{
    public static final String _DEAD_SESSION = "deadSession";
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response)throws Exception{
        ActionForward fw;
        Usuario user = (Usuario) request.getSession().getAttribute(_USER);
        if (user == null)
            fw = mapping.findForward(_DEAD_SESSION);
        else
            fw = super.execute(mapping, form, request, response);
        return fw;
    }
    /*private static final String _SESSION_H = "_SESSION_HIB";
    private static final String _TRX_H = "_TRX_HIB";
    private static final String EXCEPTION = "exception";
    public static final String _USER = "_USER";
    public static final String _MENU = "_MENU";

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
        ActionForward actionForward = null;									
        synchronized (request.getSession()) {
        Session session = null;
        Transaction tx = null;
            try{
                init(request);
                session = getSession(request);
                actionForward  = super.execute(mapping, form, request,response);
                tx = getTx(request);
                if (tx != null)
                    tx.commit();
            }catch(Throwable e){
                if (tx!=null) tx.rollback();
                request.setAttribute(EXCEPTION, e);
                actionForward = mapping.findForward(EXCEPTION);
                System.out.println(e.toString());
            }finally{
                if(session!=null){
                    request.getSession().setAttribute(_SESSION_H, null);
                    session.close();
                }
            }
        }
        return actionForward;
    }
    
    protected void init(HttpServletRequest request)throws HibernateException{
        SessionFactory sf = getSessionFactory();
        Object obj = request.getSession().getAttribute(_SESSION_H); 
        if(!isValidSession(obj)){
            Session ses = sf.openSession();
            ses.setFlushMode(FlushMode.AUTO);
            request.getSession().setAttribute(_SESSION_H, ses);
            Transaction tx  = ses.beginTransaction(); 
            request.getSession().setAttribute(_TRX_H, tx);			
        }				
    }
    
    public Session getSession(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(_SESSION_H);
        Session session = (Session)obj; 
        return session;
    }
    
    public Transaction getTx(HttpServletRequest request) {
        Transaction tx  = (Transaction)request.getSession().getAttribute(_TRX_H);		
        return tx;
    }
    
    public static boolean isValidSession(Object obj){
        if (obj==null )return false;
        
        if (obj instanceof Session) {
            Session sess = (Session) obj;
            if (sess.isConnected() && sess.isOpen())
            return true;
        }
        return false;
    }
	
    public static Usuario getUserInSession(HttpServletRequest request){
        HttpSession session  = request.getSession();
        Object obj = session.getAttribute(_USER);
        return (Usuario)obj;
    }*/
}